package repositories

import (
	"log"
	"qimo_work/config"
	"qimo_work/models"
)

// repositories/favorite_repository.go
type FavoriteWithDetails struct {
	models.PostFavorite
	Username  string
	PostTitle string
}

// UpdatePostMetrics 更新文章的浏览量、点赞数和收藏数
func UpdatePostMetrics(id uint, views uint, likes uint, favorites uint) error {
	var post models.Post

	// 获取当前文章
	if err := config.DB.First(&post, id).Error; err != nil {
		log.Println("Error fetching post by ID:", err)
		return err
	}

	// 更新文章的浏览量、点赞数和收藏数
	post.Views += views
	post.Likes += likes
	post.Favorites += favorites

	// 更新文章
	if err := config.DB.Save(&post).Error; err != nil {
		log.Println("Error updating post metrics:", err)
		return err
	}

	return nil
}

func AddToFavorites(userID uint, postID uint) error { // 修改为 postID
	// 检查是否已经收藏过
	var existingFavorite models.PostFavorite
	if err := config.DB.Where("user_id = ? AND post_id = ?", userID, postID).First(&existingFavorite).Error; err == nil { // 修改为 postID
		// 如果已有收藏，返回
		log.Println("Post is already in favorites")
		return nil
	}

	// 创建新的收藏记录
	favorite := models.PostFavorite{
		UserID: userID,
		PostID: postID, // 修改为 postID
	}

	// 插入收藏记录到数据库
	if err := config.DB.Create(&favorite).Error; err != nil {
		log.Println("Error adding post to favorites:", err)
		return err
	}

	// 更新文章的收藏数
	err := UpdatePostMetrics(postID, 0, 0, 1) // 修改为 postID
	if err != nil {
		log.Println("Error updating post metrics after adding to favorites:", err)
		return err
	}

	return nil
}
func GetUserFavorites(userID uint) ([]FavoriteWithDetails, error) {
	var favorites []FavoriteWithDetails

	// 使用原生SQL进行关联查询
	err := config.DB.Raw(`
        SELECT 
            post_favorites.*,
            users.username as username,
            posts.title as post_title
        FROM post_favorites
        LEFT JOIN users ON users.id = post_favorites.user_id
        LEFT JOIN posts ON posts.id = post_favorites.post_id
        WHERE post_favorites.user_id = ?
    `, userID).Scan(&favorites).Error

	if err != nil {
		return nil, err
	}

	return favorites, nil
}

// 取消收藏文章
func RemoveFromFavorites(postID uint) error {
	err := config.DB.Where("post_id = ?", postID).
		Delete(&models.PostFavorite{}).Error

	return err
}

// CreateAttachment 创建附件记录
func CreateAttachment(attachment models.Attachment) error {
	// 启动一个数据库事务
	tx := config.DB.Begin()

	// 确保事务在结束时正确提交或回滚
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			log.Println("Transaction rolled back due to panic:", r)
		}
	}()

	// 插入附件记录
	if err := tx.Create(&attachment).Error; err != nil {
		tx.Rollback()
		log.Println("Error creating attachment:", err)
		return err
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		log.Println("Error committing transaction:", err)
		return err
	}

	// 记录成功日志
	log.Println("Attachment created successfully:", attachment.ID)

	return nil
}

// GetAttachmentsByPostID 根据文章ID获取附件列表
func GetAttachmentsByPostID(postID uint) ([]models.Attachment, error) {
	var attachments []models.Attachment

	if err := config.DB.Where("post_id = ?", postID).Find(&attachments).Error; err != nil {
		log.Println("Error fetching attachments:", err)
		return nil, err
	}

	return attachments, nil
}

// GetAttachments 获取所有附件记录
func GetAttachments() ([]models.Attachment, error) {
	var attachments []models.Attachment

	if err := config.DB.Find(&attachments).Error; err != nil {
		log.Println("Error fetching attachments:", err)
		return nil, err
	}

	return attachments, nil
}

// DeleteAttachmentByID 根据ID删除附件
func DeleteAttachmentByID(id uint) error {
	// 启动一个数据库事务
	tx := config.DB.Begin()

	// 确保事务在结束时正确提交或回滚
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			log.Println("Transaction rolled back due to panic:", r)
		}
	}()

	// 删除附件记录
	if err := tx.Delete(&models.Attachment{}, id).Error; err != nil {
		tx.Rollback()
		log.Println("Error deleting attachment:", err)
		return err
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		log.Println("Error committing transaction:", err)
		return err
	}

	// 记录成功日志
	log.Println("Attachment deleted successfully:", id)

	return nil
}
